/**
 * Created by ZHOUSH on 12/11/2015.
 */
var oracle = require('oracledb');
var Promise = require('promise');
var execute = function (conn, sql) {
    var pexe = Promise.denodeify(conn.execute);
    return pexe.call(conn, sql, [], {
        resultSet: true
    }).then(function (resp) {
        var rs = resp.resultSet;
        var pgr = Promise.denodeify(rs.getRows);
        var data = [];
        var next = function (rows) {
            if (!rows || rows.length == 0) {
                return Promise.resolve(data);
            } else {
                data = data.concat(rows);
                return pgr.call(rs, 50).then(next);
            }
        };
        return pgr.call(rs, 50).then(next).then(function (data) {
            var stream = function (cell) {
                if (typeof cell == "object" && cell && cell.readable) {
                    return new Promise(function (resolver, rejector) {
                        try {
                            cell.setEncoding('utf-8');
                            var str = '';
                            cell.on('data', function (result) {
                                str += result;
                            });
                            cell.on('end', function () {
                                resolver(str);
                            });
                        } catch (ex) {
                            rejector(ex);
                        }
                    });
                } else {
                    return Promise.resolve(cell);
                }
            };
            var obj = [];
            var rowVal = function (i) {
                var entry = {};
                return Promise.all(data[i].map(stream)).then(function (res) {
                    res.forEach(function (cell, idx) {
                        entry[rs.metaData[idx].name] = cell;
                    });
                    obj.push(entry);
                    if (i < data.length - 1) {
                        return rowVal(i + 1);
                    } else {
                        return Promise.denodeify(rs.close).call(rs).then(function () {
                            console.log('RESULT SET CLOSED');
                            return obj;
                        });
                    }
                });
            };
            return rowVal(0);
        });
    });
};
//var connStr = '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = hllpprd.oocl.com)(PORT = 1521)) (CONNECT_DATA = (SERVER=DEDICATED) (SID = hllpprd1)))';
//var kp = {
//    PRD: ['HLLP_SUPP', 'Hllptemp01']
//};
//var pdb = Promise.denodeify(oracle.getConnection);
//pdb.call(oracle, {
//    user: kp.PRD[0],
//    password: kp.PRD[1],
//    connectString: connStr
//}).then(function (conn) {
//    return execute(conn, "select sql_str from LLP_RPT_ORACLE_SQL WHERE ora_rpt_rdf_name = 'RPT_MQC_TRACKING'")
//        .then(console.log, console.log)
//        .then(function () {
//            console.log('RELEASE');
//            return Promise.denodeify(conn.release).call(conn);
//        });
//}).catch(function (err) {
//    console.log(err.stack);
//});
exports.execute = execute;